#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/8
# @Author :CJX
# @File   :DHT11.py
import RPi.GPIO as GPIO
import dht11
import time
import pymysql

# initialize GPIO
def DHT11(temperature,humidity):
    con = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='!qAz2WsX3edc',
        db='ph',
        charset='utf8'
    )
    cur = con.cursor()
    address = "DHT11"
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()

    instance = dht11.DHT11(pin = 18)  # DHT11连接的引脚
    a = 0
    while a <= 10:
        result = instance.read()
        if result.is_valid():
            temperature = '%-3.1f' % result.temperature
            humidity = '%-3.1f' % result.humidity
            time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            cur.executemany(
                "INSERT DHT11(address,time,temperature,humidity) VALUE(%s,%s,%s,%s)",
                [(address, time1, temperature, humidity)])
            con.commit()
            cur.close()
            a = 11
            return temperature, humidity
        else:
            a = 0
